package com.ecar.api.rest.common;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ecar.api.rest.AbstractResource;
import com.ecar.api.service.common.AddressService;
import com.ecar.api.service.common.DictionaryService;
import com.ecar.api.service.common.ExceptionHandleService;
import com.ecar.api.service.common.NotifyService;
import com.ecar.api.service.driver.DriverService;
import com.ecar.api.service.manager.StaffService;
import com.ecar.api.service.order.OrderService;
import com.ecar.api.support.dto.order.Constants;
import com.ecar.api.support.dto.order.DriverWilddogDto;
import com.ecar.api.support.util.DateUtil;
import com.ecar.api.support.util.OrderUtil;
import com.ecar.api.support.util.Props;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.WilddogUtil;
import com.ecar.common.annotation.ResponseFilter;
import com.ecar.common.dto.DataBean;
import com.ecar.common.dto.ParamBean;
import com.ecar.common.util.BeanUtils;
import com.ecar.common.util.DataValidateUtil;
import com.ecar.common.util.HttpUtils;
import com.ecar.common.util.JSONUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.entity.Address;
import com.ecar.core.common.entity.Dictionary;
import com.ecar.core.driver.entity.Driver;
import com.ecar.core.driver.entity.ExceptionHandle;
import com.ecar.core.driver.entity.Idea;
import com.ecar.core.order.entity.Order;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 类PublicController.java的实现描述：实现投诉相关业务处理
 * 
 * @author fire 2017-10-18 15:02:57
 */
@Controller
@Scope("prototype")
@Path("/public")
public class PublicController extends AbstractResource{
	
	@Autowired
	NotifyService notifyService;
	
	@Autowired
	AddressService addressService;
	
	@Autowired
	DictionaryService dictionaryService;
	
	@Autowired
	DriverService driverService;
	
	@Autowired
	static
	OrderService orderService;
	
	@Autowired
	ExceptionHandleService exceptionHandleService;
	
	@Context
	HttpServletRequest request;

	@Autowired
	StaffService staffService;
	
	private String generateCaptcha() {
		String captcha = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			captcha += random.nextInt(10);
		}
		return captcha;
	}
	
	public static void sendF2FOrder(Order order){
		DriverWilddogDto driverWilddogDto=new DriverWilddogDto();
		BeanUtils.copySolidProperties(order, driverWilddogDto);
		driverWilddogDto.setCreateTime(DateUtil.dateToMS(order.getStartTime()));
		driverWilddogDto.setCarpool(order.getOrderNum());
		driverWilddogDto.setPassengerName(order.getPassengerPhone());
		driverWilddogDto.setPhone(order.getPassengerPhone());
		driverWilddogDto.setPassengerId(order.getPassengerId());
		Map<String, Object> map=DataValidateUtil.objectToMap(DataValidateUtil.parseNull(driverWilddogDto));
		HashMap<String, Object> tempMap = new HashMap<String, Object>();
		tempMap.put(order.getOrderNum(), map);
		WilddogUtil.sendNowOrderToDriver(order.getDriverId(), tempMap);
		List<Order> orders=orderService.selectOrderByParentOrder(order.getParentOrder());
		OrderUtil.sortOrder(orders);
	}
	
	
	@GET
	@Path("/{phone}/deletDriverLoginCount")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean deletDriverLoginCount(@PathParam("phone") String phone) {
		
		long result=driverService.deletLoginCount(phone);
		if(result==1){
			return new DataBean(200,new JSONObject(),"清空司机错误登陆次数操作成功");
		}else{
			return new DataBean(400,new JSONObject(),"清空司机错误登陆次数操作失败");
		}
		
	}
	
	/**
	 * 工作人员后台登录
	 * @param param
	 * @return
	 */
	@POST
	@Path("/staff/login")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean staffLogin(JSONObject param) {
		try {
			if(!parse(param) && this.fields==null) return new DataBean(400, new JSONObject(),"参数错误。");
//			String paramStr = param.getString("params");
//			if (StringUtil.isEmpty(paramStr))
//			return new DataBean(400, "登录参数错误！");

//			ParamBean pb = JSONUtil.deserialize(this.fields, ParamBean.class);
//			JSONObject fields = pb.getFields();
//			if (fields == null)
//				return new DataBean(400, "登录参数错误！");

			String ip = HttpUtils.getRemoteHost(request);
			//String ip ="127.0.0.1";
			return staffService.login(fields, ip);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, "登录失败，服务器错误。");
		}
	}
	/**
	 * 通过手机和验证码修改密码
	 * @param phone
	 * @param captcha
	 * @return
	 */
	@POST
	@Path("/{phone}/{captcha}/password")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean forgetPassword(@PathParam("phone") String phone, @PathParam("captcha") String captcha) {
		try {
			String pwd = request.getParameter("pwd");
			if (StringUtil.isEmpty(captcha) || StringUtil.isEmpty(phone) || StringUtil.isEmpty(pwd))
				return new DataBean(400, "参数错误，手机号和验证码不能为空。");

			Pattern pattern = Pattern.compile("^[A-Za-z0-9!@\\$\\^\\*\\(\\)_`~\\-=,\\.;:<>\\?\\|]{6,22}$");
			Matcher matcher = pattern.matcher(pwd);
			if (!matcher.matches()) return new DataBean(403, "密码为6至22位字母数字和非特殊字符");

			return staffService.setPasswordByPhone(pwd, phone, captcha);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, "修改密码失败。");
		}
	}
	
	/**
	 * 发送手机验证码
	 * @author fire
	 * @param phone
	 * @return
	 */
	@GET
	@Path("/{phone}/verify")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean captcha(@PathParam("phone") String phone) {
		try {
			Pattern patternP = Pattern.compile("^((13[0-9])|(14[5|7])|(15([0-9]))|(17([0-9]))|(18[0-9]))\\d{8}$");
			Matcher matcherP = patternP.matcher(phone);
			if (!matcherP.matches()) return new DataBean(403,new JSONObject(),"手机号有误");
			
			//有效时长
			final int EXPIRE = 1800;
			//验证码
			String captcha = generateCaptcha();
			//设置验证码的有效时间
			String result = Redis.c.setex(Redis.K.CAPTCHA.to(phone), EXPIRE, captcha);
			//感觉没啥用的一段代码，暂且注释在这
			/*if (!"ok".equalsIgnoreCase(result)) {
				Redis.c.setex(Redis.K.CAPTCHA.to(phone), EXPIRE, captcha);
			}*/
			if (StringUtil.isEmpty(captcha)) return new DataBean(400,new JSONObject(),"验证码不能为空");

			log.debug("sending captcha: ******" + captcha + "******");
			//获取模版格式：模版在config.properties里
			String content = Props.getValue("sms.msg.captcha");
			//根据模版进行数据格式化，验证码填写进content字符串里的｛0｝位置
			content = MessageFormat.format(content, captcha);
			//发送短信
			boolean success = notifyService.sendCaptcha(phone, content);
			if (!success) return new DataBean(500,new JSONObject(),"发送验证码失败。");

			return new DataBean(200,new JSONObject(),"发送验证码成功。");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(),"发送验证码失败。");
		}
	}
	
	/**
	 * 发送司机手机邀请验证码
	 * @author fire
	 * @param phone
	 * @return
	 */
	@GET
	@Path("/{driverId}/{phone}/{type}/invite")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean invite(@PathParam("phone") String phone,@PathParam("driverId")String driverId,@PathParam("type")String type) {
		try {
			Pattern patternP = Pattern.compile("^((13[0-9])|(14[5|7])|(15([0-9]))|(17([0-9]))|(18[0-9]))\\d{8}$");
			Matcher matcherP = patternP.matcher(phone);
			if (!matcherP.matches()) return new DataBean(403, new JSONObject(),"手机号有误");
			
			
			Driver driver=null;
			//获取模版格式：模版在config.properties里
			String content = "";
			switch(Integer.valueOf(type)){
			case 1:
				content = Props.getValue("sms.msg.invite.passenger");
				break;
			case 2:
				driver=driverService.selectByPhone(phone);
				if(driver!=null){
					return new DataBean(403,new JSONObject(),"司机已注册");
				}
				content = Props.getValue("sms.msg.invite.driver");
			default:
				break;
			}
			driver=driverService.selectByPrimaryKey(driverId);
			//根据模版进行数据格式化，验证码填写进content字符串里的｛0｝位置
			content = MessageFormat.format(content, driver.getName());
			//发送短信
			boolean success = notifyService.sendCaptcha(phone, content);
			if (!success){
				log.info("发送失败");
				return new DataBean(500, new JSONObject(),"发送邀请失败。");
				}

			log.info("发送成功");
			return new DataBean(200,new JSONObject(),"发送邀请码成功。");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(),"发送邀请码失败。");
		}
	}
	
	/**
	 * 设置常用地
	 * @param phone
	 * @return
	 */
	@ResponseFilter(target=Address.class,fields={})
	@POST
	@Path("/setAddress")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean setAddress(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			Address address = JSONUtil.deserialize(this.fields, Address.class);
			if(StringUtil.isEmpty(address.getUserId())||StringUtil.isEmpty(address.getUserType().toString())||
					StringUtil.isEmpty(address.getAddress())||StringUtil.isEmpty(address.getAddressType().toString())||StringUtil.isEmpty(address.getPoint()))return new DataBean(500,new JSONObject(),"参数不能为空");
			log.info("用户{},设置常用地：{}" ,address.getUserId(),this.fields.toString());
			return addressService.insert(address);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONArray(),"设置常用地失败。");
		}
	}
	/**
	 * 获取常用地
	 * @param phone
	 * @return
	 */
	@ResponseFilter(target=Address.class,fields={})
	@GET
	@Path("/{userId}/{userType}/getAddress")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getAddress(@PathParam("userId")String userId,@PathParam("userType")Integer type) {
		try {
			if (StringUtil.isEmpty(userId)) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			log.info("用户{},用户类型：{},查询常用地" ,userId,type);
			return addressService.selectByUserIdAndUserType(userId,type);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONArray(),"获取常用地失败。");
		}
	}
	
	/**
	 * 获取评论标签
	 * @param phone
	 * @return
	 */
	@ResponseFilter(target=Dictionary.class,fields={})
	@GET
	@Path("/getTips")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getTips() {
		try {
			return new DataBean(200, dictionaryService.selctByParentNode("01"),"查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(),"查询失败");
		}
	}
	
	/**
	 * 司机订单异常
	 * @author fire
	 * @param 
	 */
	@POST
	@Path("/exception")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean submitException(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400,new JSONObject(), "请求参数格式错误！");
			log.info("司机:{},意见反馈：{}" , this.fields.getString("driverId") ,this.fields.toString());
			if(!this.fields.has("driverId") || !this.fields.has("orderId") || !this.fields.has("exceptionCause"))return new DataBean(403,new JSONObject(),"参数不能为空");
			return exceptionHandleService.insert(this.fields);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(), "用户登陆失败。");
		}
	}
	
	/**
	 * App版本号
	 * @author fire
	 * @param 
	 */
	@GET
	@Path("/{appType}/appVersion")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean queryAppVersion(@PathParam("appType")String appType) {
		try {
			List<Dictionary> dictionaryList = dictionaryService.selctByParentNodeAppVersions(Constants.APP_VERSION);
			Map<String,Object> map=new HashMap<String,Object>();
			for(Dictionary dictionary:dictionaryList){
				if(dictionary.getTheNode().equals(appType)){
					
					String[] remarks=dictionary.getRemark().split("#");
					map.put("name", dictionary.getName());
					map.put("appVersion", remarks[0]);
					map.put("appAdrr", remarks[1]);//app服务器地址
					
				}
			}
			
			return new DataBean(200,map,"App版本查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(), "App版本查询失败。");
		}
	}
	
}
